import time

from django.shortcuts import render, redirect

# Create your views here.
from django.http.response import HttpResponse
from django.views.decorators.cache import cache_page


def connect_redis_test(request):
    from django_redis import get_redis_connection

    conn = get_redis_connection("default")

    # 设置缓存，带有不同的超时时间和前缀
    conn.set('another_key', 'value')

    # 获取缓存
    value = conn.get('another_key')
    print(value)  # 应该输出 'value'

    return HttpResponse('欢迎光临，当前时间戳：' + str(time.time()))


import time


# @never_cache  禁用缓存
def global_cache_test(request):
    t = time.time()
    return HttpResponse(f'全站缓存测试，时间戳：t:{t}')


@cache_page(120, cache='default', key_prefix='redis_app_view_cache_test')
def view_cache_test(request, num=10):
    t = time.time()
    print(3333333333)
    return HttpResponse(f'视图缓存测试，时间戳：t:{t},num:{num}')

from django.core.cache import cache

def lower_level_cache(request):
    cache.key_prefix = 'first_app'
    t = time.time()
    cache.set('key','value',timeout=20)
    manul_set=cache.ttl('key')
    #
    # cache.expire('key',timeout=40)
    return HttpResponse(f'缓存字段，时间戳：t:{t}，manul_set:{manul_set}')

#session缓存
def login(request):
    if request.method=='GET':
        return render(request,'redis_app/login.html')
    elif request.method=='POST':
        uname = request.POST.get('uname')
        password = request.POST.get('password')
        if uname == 'root' and password =='root':
            #登录成功
            #将用户名存放到session
            request.session['uname'] = uname
            return redirect('redis_app:index')
        else:
            return redirect('redis_app:login')

def index(request):
    uname = request.session.get('uname')
    if uname:  #跳转到主页
        return render(request,'redis_app/index.html',{'uname':uname})
    else:
        return redirect('redis_app:login')





